<template>
  <div class="product-list">
    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-card class="filter-card">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="关键词">
            <el-input v-model="searchForm.keyword" placeholder="搜索商品名称或描述" clearable />
          </el-form-item>
          <el-form-item label="分类">
            <el-cascader
              v-model="searchForm.category"
              :options="categories"
              :props="{ checkStrictly: true }"
              clearable
              placeholder="选择商品分类"
            />
          </el-form-item>
          <el-form-item label="价格区间">
            <el-input-number v-model="searchForm.minPrice" :min="0" placeholder="最低价" />
            <span class="price-separator">-</span>
            <el-input-number v-model="searchForm.maxPrice" :min="0" placeholder="最高价" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 商品展示区域 -->
    <div class="products-section">
      <el-row :gutter="20">
        <el-col v-for="product in products" :key="product.id" :xs="24" :sm="12" :md="8" :lg="6">
          <el-card class="product-card" :body-style="{ padding: '0px' }">
            <div class="product-image" @click="viewProductDetail(product.id)">
              <el-image :src="product.imageUrl" fit="cover">
                <template #error>
                  <div class="image-placeholder">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div v-if="product.discountRate" class="discount-tag">
                {{ Math.round((1 - product.discountRate) * 100) }}% OFF
              </div>
            </div>
            <div class="product-info">
              <h3 class="product-name" @click="viewProductDetail(product.id)">{{ product.name }}</h3>
              <p class="product-description">{{ product.description }}</p>
              <div class="product-price">
                <span class="current-price">¥{{ product.price }}</span>
                <span v-if="product.discountRate" class="original-price">
                  ¥{{ (product.price / product.discountRate).toFixed(2) }}
                </span>
              </div>
              <div class="product-meta">
                <span class="credit-score">所需信用分: {{ product.minCreditScore }}</span>
                <span v-if="product.isInstallmentAvailable" class="installment-tag">支持分期</span>
              </div>
              <div class="product-actions">
                <el-button type="primary" @click="handleAddToCart(product)">加入购物车</el-button>
                <el-button type="success" @click="handleBuyNow(product)">立即购买</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[12, 24, 36, 48]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 商品详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="商品详情"
      width="70%"
      :before-close="handleDetailDialogClose"
    >
      <product-detail
        v-if="detailDialogVisible"
        :product-id="selectedProductId"
        @close="detailDialogVisible = false"
      />
    </el-dialog>

    <!-- 购买对话框 -->
    <el-dialog
      v-model="purchaseDialogVisible"
      title="确认订单"
      width="50%"
      :before-close="handlePurchaseDialogClose"
    >
      <purchase-form
        v-if="purchaseDialogVisible"
        :product="selectedProduct"
        @submit="handlePurchaseSubmit"
        @cancel="purchaseDialogVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Picture } from '@element-plus/icons-vue'
import ProductDetail from '@/components/credit/ProductDetail.vue'
import PurchaseForm from '@/components/credit/PurchaseForm.vue'
import { getProducts, getCategories } from '@/api/product'

export default {
  name: 'ProductList',
  components: {
    ProductDetail,
    PurchaseForm,
    Picture
  },
  setup() {
    const router = useRouter()
    const products = ref([])
    const categories = ref([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(12)
    const detailDialogVisible = ref(false)
    const purchaseDialogVisible = ref(false)
    const selectedProductId = ref(null)
    const selectedProduct = ref(null)

    const searchForm = reactive({
      keyword: '',
      category: null,
      minPrice: null,
      maxPrice: null
    })

    // 加载商品数据
    const loadProducts = async () => {
      try {
        const response = await getProducts({
          page: currentPage.value - 1,
          size: pageSize.value,
          ...searchForm
        })
        products.value = response.content
        total.value = response.totalElements
      } catch (error) {
        ElMessage.error('加载商品列表失败')
      }
    }

    // 加载分类数据
    const loadCategories = async () => {
      try {
        categories.value = await getCategories()
      } catch (error) {
        ElMessage.error('加载商品分类失败')
      }
    }

    // 搜索处理
    const handleSearch = () => {
      currentPage.value = 1
      loadProducts()
    }

    // 重置搜索
    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = null
      })
      handleSearch()
    }

    // 查看商品详情
    const viewProductDetail = (productId) => {
      selectedProductId.value = productId
      detailDialogVisible.value = true
    }

    // 加入购物车
    const handleAddToCart = (product) => {
      // TODO: 实现加入购物车功能
      ElMessage.success('已加入购物车')
    }

    // 立即购买
    const handleBuyNow = (product) => {
      selectedProduct.value = product
      purchaseDialogVisible.value = true
    }

    // 处理购买提交
    const handlePurchaseSubmit = async (orderData) => {
      try {
        // TODO: 实现购买提交
        ElMessage.success('订单提交成功')
        purchaseDialogVisible.value = false
        router.push('/credit/orders')
      } catch (error) {
        ElMessage.error('订单提交失败')
      }
    }

    // 分页处理
    const handleSizeChange = (val) => {
      pageSize.value = val
      loadProducts()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadProducts()
    }

    // 对话框关闭处理
    const handleDetailDialogClose = () => {
      detailDialogVisible.value = false
      selectedProductId.value = null
    }

    const handlePurchaseDialogClose = () => {
      purchaseDialogVisible.value = false
      selectedProduct.value = null
    }

    onMounted(() => {
      loadProducts()
      loadCategories()
    })

    return {
      products,
      categories,
      searchForm,
      total,
      currentPage,
      pageSize,
      detailDialogVisible,
      purchaseDialogVisible,
      selectedProductId,
      selectedProduct,
      handleSearch,
      resetSearch,
      viewProductDetail,
      handleAddToCart,
      handleBuyNow,
      handlePurchaseSubmit,
      handleSizeChange,
      handleCurrentChange,
      handleDetailDialogClose,
      handlePurchaseDialogClose
    }
  }
}
</script>

<style lang="scss" scoped>
.product-list {
  padding: 20px;

  .search-section {
    margin-bottom: 20px;

    .filter-card {
      .search-form {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
      }

      .price-separator {
        margin: 0 10px;
      }
    }
  }

  .products-section {
    margin-bottom: 20px;

    .product-card {
      margin-bottom: 20px;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
      }

      .product-image {
        position: relative;
        height: 200px;
        cursor: pointer;

        .el-image {
          width: 100%;
          height: 100%;
        }

        .image-placeholder {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: #f5f7fa;
          color: #909399;
          font-size: 24px;
        }

        .discount-tag {
          position: absolute;
          top: 10px;
          right: 10px;
          background-color: #f56c6c;
          color: white;
          padding: 2px 8px;
          border-radius: 4px;
          font-size: 12px;
        }
      }

      .product-info {
        padding: 14px;

        .product-name {
          margin: 0;
          font-size: 16px;
          cursor: pointer;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;

          &:hover {
            color: #409eff;
          }
        }

        .product-description {
          margin: 8px 0;
          font-size: 14px;
          color: #666;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }

        .product-price {
          margin: 8px 0;

          .current-price {
            font-size: 18px;
            color: #f56c6c;
            font-weight: bold;
          }

          .original-price {
            margin-left: 8px;
            font-size: 14px;
            color: #999;
            text-decoration: line-through;
          }
        }

        .product-meta {
          display: flex;
          justify-content: space-between;
          margin: 8px 0;
          font-size: 12px;
          color: #666;

          .installment-tag {
            color: #67c23a;
          }
        }

        .product-actions {
          display: flex;
          gap: 10px;
          margin-top: 10px;
        }
      }
    }
  }

  .pagination-section {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}
</style> 